<script setup lang="ts">
import { ref } from 'vue'
import type { PaginationProps } from 'naive-ui/es/pagination/src/Pagination'
import type { ApiPageResp } from '@/type/ApiType.ts'
import type { RowData } from 'naive-ui/es/data-table/src/interface'
import type { DataTableInst, SelectGroupOption, SelectOption, UploadFileInfo } from 'naive-ui'
import {
  type CascaderOption,
  type DataTableColumn,
  NButton,
  NCascader,
  NFlex,
  NRadioGroup,
  NTimePicker,
  NTreeSelect,
  NUpload,
  type TreeSelectOption,
} from 'naive-ui'
import type { InternalRowData } from 'naive-ui/es/data-table/src/interface.js'
import { ComponentEnum } from '@/enum/ComponentEnum.ts'
import { ArrayUtil } from '@/util/ArrayUtil.ts'
import { BusinessEnum } from '@/enum/ApiEnum.ts'
import Save from '@/infrastructure/PeaceDataTable/Save.vue'
import Detail from '@/infrastructure/PeaceDataTable/Detail.vue'
import { initPeaceColumn } from '@/infrastructure/PeaceDataTable/util/InitColumnUtil.ts'
import { SaveConfig } from '@/components/type/SaveConfig'
import { TableConfig } from '@/components/type/TableConfig'
import { PeaceColumn } from '@/components/type/PeaceColumn'
import { PeaceActionBtn } from '@/components/type/PeaceActionBtn'
import { ObjectUtil } from '@/util/ObjectUtil'
import PeaceRepeatRender from '@/components/type/PeaceRepeatRender'
import TableFilter from '@/infrastructure/PeaceDataTable/component/TableFilter/index.vue'

const props = withDefaults(
  defineProps<{
    tableConfig: TableConfig,
    rowKey?: string | ((rowData: object) => string | number)
  }>(),
  {
    rowKey: (row: any) => {
      return (row:any) => {
        return row.id ?? row.key
      }
    },
  },
)
// *******************************************************************************
// *******************************init，初始化，加载********************************
// *******************************************************************************
const peaceTableConfig = ref<TableConfig>()
onMounted(() => {
  // peaceTableConfig.value = JSON.parse(JSON.stringify(props.tableConfig))
  peaceTableConfig.value = ObjectUtil.deepClone<TableConfig>(props.tableConfig)
  // peaceTableConfig.value = props.tableConfig
  peaceTableConfig.value.columns = initPeaceColumn(peaceTableConfig.value.columns,tableAction)
  loadPeaceData()
})
// 参与列筛选的字段
const filteredPeaceColumns = computed(() => {
  const filterColumn = peaceTableConfig.value?.columns.filter(column => column.filterConfig?.peaceFilterable)
  if (!filterColumn){
    return []
  }
  return showAllFilters.value ? filterColumn : filterColumn.slice(0, 3)
})
// *******************************************************************************
// *******************************列表，table，分页列表，分页table********************
// *******************************************************************************
const loading = ref(false)
const peaceTableRef = ref<DataTableInst>()
const peaceCheckedRowKeys = ref<Array<string | number>>([])
const tableData = ref<Array<RowData>>([])
const pagination = ref<PaginationProps>({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  showQuickJumper: true,
  pageSizes: [10, 20,30,60,100,200],
  onChange: (page: number) => {
    pagination.value.page = page
    loadPeaceData()
  },
  onUpdatePageSize: (size: number) => {
    pagination.value.page = 1
    pagination.value.pageSize = size
    loadPeaceData()
  },
})
// const checkUpdate = (
//   keys: Array<string | number>,
//   rows: object[],
//   meta: { row: object | undefined; action: 'check' | 'uncheck' | 'checkAll' | 'uncheckAll' },
// ) => {
//   console.log(keys, rows, meta)
// }
const loadPeaceData = async () => {
  console.log("loadPeaceData:filterValues.value",filterValues.value)
  if (ObjectUtil.isNullOrUndefined(peaceTableConfig.value?.api)) {
    throw new Error("未定义分页列表查询接口")
  }
  // 处理 range 按照 split等
  loading.value = true
  peaceTableConfig.value.api({
      ...filterValues.value,
      page: pagination.value.page,
      size: pagination.value.pageSize,
  }).then((res: ApiPageResp<RowData[]>) => {
      pagination.value.itemCount = res.total
      tableData.value = res.data
  }).finally(() => {
      loading.value = false
  })
}
// *******************************************************************************
// *******************************搜索，筛选，过滤***********************************
// *******************************************************************************
const filterValues = ref<Record<string, unknown>>({})
const showAllFilters = ref(false)
const toggleFilters = () => {
  showAllFilters.value = !showAllFilters.value
}
const handleSearch = () => {
  loadPeaceData()
}

const handleReset = () => {
  Object.keys(filterValues.value).forEach((key) => {
    filterValues.value[key] = null
  })
  nextTick(() => {
    loadPeaceData()
  })
}
// 处理离焦事件(重复渲染的离焦)
const handleInputBlur = (key:string,index:number,fieldIndex:number,peaceItem:PeaceColumn) => {
  if (ObjectUtil.isNullOrUndefined(peaceItem.filterConfig?.repeatRender)){
    return
  }
  if (peaceItem.filterConfig.repeatRender.format === PeaceRepeatRender.STRING){
    let keyVal = ""
    for (let i = 0; i < peaceItem.filterConfig.repeatRender.num; i++) {
      keyVal = keyVal + filterValues.value[key+index+fieldIndex]
      if (i < peaceItem.filterConfig.repeatRender.num - 1){
        keyVal = keyVal + peaceItem.filterConfig.repeatRender.split
      }
    }
    filterValues.value[peaceItem.filterConfig.key] = keyVal
  }
  if (peaceItem.filterConfig.repeatRender.format === PeaceRepeatRender.ARRAY){
    const keyVal = []
    for (let i = 0; i < peaceItem.filterConfig.repeatRender.num; i++) {
      keyVal.push(filterValues.value[key+index+fieldIndex])
    }
    filterValues.value[peaceItem.filterConfig.key] = keyVal
  }
}
function getRadioValue(
  peace: unknown,
  keyFiled: string | undefined,
): string | number | boolean | undefined {
  // 确保 peace 是对象且非 null
  if (typeof peace === 'object' && peace !== null) {
    const obj = peace as Record<string, unknown>
    if ('value' in obj) {
      return obj.value as string | number | boolean | undefined
    }
    if (!keyFiled) {
      throw new Error('keyFiled is not set')
    }
    return obj[keyFiled] as string | number | boolean | undefined
  }
  return undefined
}
function getRadioLabel(peace: unknown, labelFiled: string | undefined): string {
  // 确保 peace 是对象且非 null
  if (typeof peace === 'object' && peace !== null) {
    const obj = peace as Record<string, unknown>
    if ('label' in obj) {
      return obj.label as string
    }
    if (labelFiled) {
      return obj[labelFiled] as string
    }
  }
  return 'no_label'
}

// *******************************************************************************
// *******************************列表操作,增删改查,crud********************************
// *******************************************************************************
const saveConfig = ref<SaveConfig>({
  title: '保存',
  type: BusinessEnum.ADD,
  columns: [],
  dialogWidth: props.tableConfig?.saveDialogWidth,
})
const ifShowSave = ref<boolean>(false)
const batchDelAction = (rowData?: object, rowIndex?: number, item: PeaceActionBtn) => {}
const exportAction = (rowData?: object, rowIndex?: number, item: PeaceActionBtn) => {
  peaceTableRef.value?.downloadCsv({
    fileName: 'sorter-filter',
    keepOriginalData: false,
  })
}
const excelUploaderRef = ref<InstanceType<typeof NUpload> | null>(null)
const uploadedExcelList = ref<UploadFileInfo[]>([])
const importItem = ref<PeaceActionBtn>()
const importAction = (rowData?: object, rowIndex?: number, item: PeaceActionBtn) => {
  importItem.value = item
  excelUploaderRef.value?.clear()
  uploadedExcelList.value = []
  excelUploaderRef.value?.openOpenFileDialog()
}
const updateUploadedExcelList = (fileList: UploadFileInfo[]) => {
  console.log(uploadedExcelList.value, 'updateUploadedExcelList.??', fileList[0].file as File)
  const formData = new FormData()
  formData.set('file', fileList[0].file as File)
  importItem.value
    ?.api({ formData: formData, apiParams: importItem.value?.apiParams })
    .then((res) => {
      loadPeaceData()
    })
}
const delAction = (rowData: object, rowIndex: number, item: PeaceActionBtn) => {}
const ifShowDetail = ref<boolean>(false)
const detailItem = ref<PeaceActionBtn>()
const detailRowData = ref<object>()
const detailAction = (rowData: object, rowIndex: number, item: PeaceActionBtn) => {
  detailItem.value = item
  detailRowData.value = rowData
  ifShowDetail.value = true
}
const updateAction = (rowData: object, rowIndex: number, item: PeaceActionBtn) => {
  saveConfig.value.type = BusinessEnum.UPDATE
  saveConfig.value.title = '更新'
  saveConfig.value.formData = rowData
  saveConfig.value.columns = peaceTableConfig.value.columns
  ifShowSave.value = true
}
const addAction = (rowData?: object, rowIndex?: number, item: PeaceActionBtn) => {
  saveConfig.value.type = BusinessEnum.ADD
  saveConfig.value.title = '新增'
  saveConfig.value.formData = undefined
  saveConfig.value.columns = peaceTableConfig.value.columns
  ifShowSave.value = true
}
const tableAction = (rowData?: object, rowIndex?: number, item: PeaceActionBtn) => {
  if (item.business === BusinessEnum.DETAIL) {
    detailAction(rowData!, rowIndex!, item)
  }
  if (item.business === BusinessEnum.ADD) {
    addAction(rowData, rowIndex, item)
  }
  if (item.business === BusinessEnum.UPDATE) {
    updateAction(rowData!, rowIndex!, item)
  }
  if (item.business === BusinessEnum.DEL) {
    delAction(rowData!, rowIndex!, item)
  }
  if (item.business === BusinessEnum.IMPORT) {
    importAction(rowData, rowIndex, item)
  }
  if (item.business === BusinessEnum.EXPORT) {
    exportAction(rowData, rowIndex, item)
  }
  if (item.business === BusinessEnum.BATCH_DEL) {
    batchDelAction(rowData, rowIndex, item)
  }
}
</script>

<template>
  <div class="peace-data-table-container">
  <n-card>
    <TableFilter :peace-columns="peaceTableConfig?.columns"/>
  </n-card>
  <n-card class="mt-4px">
    <n-flex v-if="ArrayUtil.isNotEmpty(props.tableConfig?.headerBtnList)" class="pt-2 pb-2">
      <template v-for="(item, index) in props.tableConfig.headerBtnList" :key="index">
        <n-button
          :type="item.type ? item.type : 'default'"
          @click="tableAction(undefined, undefined, item)"
          >{{ item.name }}</n-button
        >
      </template>
    </n-flex>
    <!--
      :row-key="()=>{return 'id'}"  -->
    <n-data-table
      ref="peaceTableRef"
      remote
      :columns="peaceTableConfig?.columns as DataTableColumn[]"
      :data="tableData"
      :loading="loading"
      :pagination="pagination"
      :row-key="rowKey"
      v-model:checked-row-keys="peaceCheckedRowKeys"
    />

    <Save v-model:show="ifShowSave" :config="saveConfig" @submit="loadPeaceData"/>
    <Detail
      v-model:show="ifShowDetail"
      :data="detailRowData"
      :detail-action-btn="detailItem"
      :columns="peaceTableConfig?.columns"
      title="手机详情数据"
    />
    <n-upload
      ref="excelUploaderRef"
      @updateFileList="updateUploadedExcelList"
      :file-list="uploadedExcelList"
      :max="1"
      accept=".xls,.xlsx,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,.csv, text/csv"
      v-show="false"
    >
      <n-button>上传文件</n-button>
    </n-upload>
  </n-card>
  </div>
</template>

<style scoped></style>
